package com.neuedu.corejava.ch13.homework;
/**
 * 使用线程的同步，解决了线程共享的问题，每个线程访问到的数据都是自己操作后的数据
 * @author admin
 *
 */
public class HomeWork3 {
	//只要是Object类或其它子类都可以作为一个锁
private static final Object LOCKED = new Object();
private int count =0;
	
	public  void add(int threadId) {
		//代码块，可以使用一个对象锁定一个代码块，在代码块中控制对某个资源的共享
		//如何加锁:对线程安全共享安全的数据进行加锁，使用方法锁或代码块
		synchronized(LOCKED) {
			count++;
			System.out.println(threadId +","+count);
		}
		
		
	}
	
	public  void desc(int threadId) {
		synchronized(LOCKED) {
			count--;
			System.out.println(threadId + " ," + count);
		}
		
	}
	
	class AddClass implements Runnable{
		
		private int threadId =0;
		
		public AddClass(int id) {
			this.threadId=id;
		}
		
		@Override
		public void run() {
			for(int i=0;i<50;i++) {
				add(threadId);
				
//				try {
//					Thread.sleep(100);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
			}
			
			
		}
		
	}
	
	class DescClass implements Runnable {
		private int threadId = 0;

		public DescClass(int id) {
			this.threadId = id;
		}
		@Override
		public void run() {
			for (int i = 0; i < 50; i++) {
				desc(threadId);
				
//				try {
//					Thread.sleep(100);
//				} catch (InterruptedException e) {
//				}
			}
		}
	}


	public static void main(String[] args) {
		HomeWork3 homeWork1 = new HomeWork3();
		AddClass addClass1 =homeWork1. new AddClass(1);
		AddClass addClass2 =homeWork1. new AddClass(2);
		DescClass descClass1 =homeWork1.new DescClass(3);
		DescClass descClass2 = homeWork1.new DescClass(4);
		
		new Thread(addClass1).start();
		new Thread(addClass2).start();
		new Thread(descClass1).start();
		new Thread(descClass2).start();
		
		
		
		

	}


}
